package cn.antia.cwin.db;

import cn.antia.db.JdbcSql;
import cn.antia.cwin.Cele;

import java.util.List;
import java.util.Map;

/**
 * User: Jacob Xiao
 * Date: 2008-7-14
 * Time: 16:21:42
 */
public class MySQLCwinSQLGene extends AbstractCwinSQLGene{
	/**
	 * 取得WHERE子句的条件Ӿ�
     * @param conditions 条件
     * @return where 子句*/
	public JdbcSql getConditionSql(Map<Cele,Object> conditions){
		Object[] paraValues = new Object[conditions.size()];
		JdbcSql jdbcSql = new JdbcSql();
		jdbcSql.setValues(paraValues);
		StringBuffer sb = new StringBuffer(" where ");
		int n = 0;
		if(conditions == null || conditions.size() < 1){
			return jdbcSql;
		}
		String dbType;
        int i = 0;
        for (Map.Entry<Cele,Object> entry : conditions.entrySet()) {
            Cele ec = entry.getKey();
            Object value = entry.getValue();
            boolean isString = false;
            if (ec.getField().getDbType() == null) {
                ec.getField().setDbType("varchar");
            }
            dbType = ec.getField().getDbType().toLowerCase();
            if (dbType.indexOf("char") > -1) {
                isString = true;
            }
            if (dbType.indexOf("text") > -1) {
                continue;
            }
            if (n == 0) {
                n++;
            } else {
                sb.append(" and ");
            }
            if (isString) {
                sb.append(ec.getField().getFieldName()).append(" like ? ");
                //在两边加上通配符
                if (value.toString().indexOf("%") != 0) {
                    value = "%" + value;
                    if (value.toString().charAt(value.toString().length() - 1) != '%') {
                        value = value + "%";
                    }
                }
                paraValues[i++] = value;
            } else {
                if (dbType.indexOf("date") > -1 || dbType.indexOf("time") > -1) {
                    sb.append(ec.getField().getFieldName()).append("='").append(conditions.get(ec).toString()).append("'");
                } else {
                    sb.append(ec.getField().getFieldName()).append("=").append(conditions.get(ec).toString());
                }
            }
        }
        if(n == 0) return jdbcSql;
		jdbcSql.setSql(sb.toString());
		return jdbcSql;
	}
}
